/*
 * @Author: wuqingchun
 * @Date: 2024-01-10 19:06:00
 * @Description: 
 * @LastEditors: wuqingchun
 * @LastEditTime: 2024-01-10 20:11:54
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <time.h>
#include <syslog.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>

#include "ftpc.h"
#include "ftpc_log.h"


// 日志级别字符串定义
static char *g_apcFTPLogLevelName[] = 
{
     "DEBUG ", 
     "INFO  ", 
     "NOTICE",
     "WARN  ",
     "ERROR ", 
     "FATAL "
};

#define FTPC_LOG_LINE_MAX_LEN 2047

FTPC_LOG_S g_stFTPCLog;

void FTPC_log_Output
(
    FTPC_LOG_LEVEL_E enLevel, 
    const char* pcSrcFile, 
    unsigned int uiLineNo, 
    const char* pcFuncName, 
    const char* pcFmt, 
    ...
)
{
    va_list args;
    char szData[FTPC_LOG_LINE_MAX_LEN + 1];
    struct tm stTM;
	struct timeval stTV;
    int iLen;

    if (!BIT_TEST(g_stFTPCClient.uiFlags, FTPC_FLAG_DEBUG))
    {
        return;
    }

	gettimeofday(&stTV, NULL);
	(void)localtime_r(&stTV.tv_sec, &stTM);

    iLen = sprintf(szData, "%04d%02d%02d %02d:%02d:%02d.%06lu [%d] %s ", 
                   stTM.tm_year + 1900, stTM.tm_mon + 1, stTM.tm_mday, 
                   stTM.tm_hour, stTM.tm_min, stTM.tm_sec, stTV.tv_usec, 
                   getpid(), g_apcFTPLogLevelName[enLevel]);

	va_start(args, pcFmt);
	iLen += vsnprintf(szData + iLen, 2048 - iLen - 1, pcFmt, args);
	va_end(args);

	iLen += sprintf(szData + iLen, ", %s:%u:%s\n", pcSrcFile, uiLineNo, pcFuncName);
	szData[iLen] = '\0';
    (void)write(g_stFTPCLog.iFd, szData, iLen);
}

// 日志初始化
int FTPC_log_Init(void)
{
    int iFd = open("ftpc.log", O_CREAT|O_APPEND|O_WRONLY, 0644);
    if (iFd == -1)
    {
        printf("open ftpc.log error, %s\n", strerror(errno));
        return -1;
    }

    g_stFTPCLog.iFd = iFd;
    g_stFTPCLog.iLevel = 0xff;

    return 0;
}

void FTPC_log_Exit(void)
{
    if (g_stFTPCLog.iFd != -1)
    {
        close(g_stFTPCLog.iFd);
        g_stFTPCLog.iFd = -1;
    }
}